package com.jdew.thkj.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.jdew.thkj.R;
import com.jdew.thkj.activity.LoginActivity;
import com.jdew.thkj.activity.SortsActivity;
import com.jdew.thkj.activity.TbProductDetailActivity;
import com.jdew.thkj.adapter.CatesAdapter;
import com.jdew.thkj.adapter.CatesAdapter2;
import com.jdew.thkj.base.BaseFragment;
import com.jdew.thkj.bean.CatesBean;
import com.jdew.thkj.dialog.CommonDialog;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.onitemInterface.OnItemClickListener;
import com.jdew.thkj.utils.DeviceUtils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.utils.WeiboDialogUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangzai on 2018/5/24.
 */

public class HotFragment extends BaseFragment implements  View.OnClickListener {
    @Bind(R.id.tvRefresh)
    TextView tvRefresh;
    @Bind(R.id.image)
    ImageView image;
    @Bind(R.id.swipe_target)
    RecyclerView recyclerView;
    @Bind(R.id.tv_load_prompt)
    TextView tvLoadPrompt;
    @Bind(R.id.arror_top)
    ImageView arrorTop;
    @Bind(R.id.nonetwork)
    TextView nonetwork;
    private SortsActivity activity;
    private CatesAdapter adapter;
    private CatesAdapter2 adapter2;
    private List<CatesBean.DataBeanX.DataBean> list = new ArrayList<>();
    private String ItemId;
    private int page=1;
    private String Adzoneid;
    private String Siteid;

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_sorts;
    }

    @Override
    protected void onCreateViewT() {
        activity = (SortsActivity) getActivity();
        if(!EventBus.getDefault().isRegistered(this)){//加上判断
            EventBus.getDefault().register(this);
        }
        arrorTop.setOnClickListener(this);
        nonetwork.setOnClickListener(this);
        adapter = new CatesAdapter(activity, list);
        adapter2 = new CatesAdapter2(activity, list);
        if(activity.recycleType.equals("1")){
            setRecycleType1();
        }else{
            setRecycleType2();
        }
        adapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (!RegexValidateUtils.isFastClick()) {
                   return;
                }
                if (activity.sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(activity, LoginActivity.class));
                } else if (activity.sp.getString("UserSjPhone", "").equals("") && (!activity.sp.getString("SpareTwo", "").equals("1"))) {
                    toset("检测到您还没有绑定上级,请到我的页面绑定上级");
                } else {
                    ItemId = list.get(position).getGoods_id() + "";
                    toDetail();
                }
            }
        });
        adapter2.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (!RegexValidateUtils.isFastClick()) {
                    return;
                }

                if (activity.sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(activity, LoginActivity.class));
                }else if (activity.sp.getString("UserSjPhone", "").equals("") && (!activity.sp.getString("SpareTwo", "").equals("1"))) {
                    toset("检测到您还没有绑定上级,请到我的页面绑定上级");
                } else {
                    ItemId = list.get(position).getGoods_id() + "";
                    toDetail();
                }
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int mScrollThreshold;

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                boolean isSignificantDelta = Math.abs(dy) > mScrollThreshold;
                if (isSignificantDelta) {
                    if (dy > 0) {
                        onScrollUp();
                    } else {
                        if (!recyclerView.canScrollVertically(-1)) {
                            onScrollDown();
                        }
                    }
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

            }
        });
    }

    /**
     * 下滑监听
     */
    private void onScrollDown() {
//下滑时要执行的代码
        arrorTop.setVisibility(View.GONE);
    }

    /**
     * 上滑监听
     */
    private void onScrollUp() {
//上滑时要执行的代码
        arrorTop.setVisibility(View.VISIBLE);
    }

    public void RequestData() {
        if (!DeviceUtils.isNetworkAvalible(activity)) {
            recyclerView.setVisibility(View.GONE);
            nonetwork.setVisibility(View.VISIBLE);
            ToastUtils.getInstance(activity).showMessage("网络连接错误请检查!");
            return;
        } else {
            recyclerView.setVisibility(View.VISIBLE);
            nonetwork.setVisibility(View.GONE);
        }
//        if (null == activity.networkProgressDialog) {
//            activity.networkProgressDialog = NetworkProgressDialog.createDialog(activity);
//        }
//        activity.networkProgressDialog.show();
        activity.mWeiboDialog = WeiboDialogUtils.createLoadingDialog(activity);
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetCateList(activity.sort,"2",page+"").observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<CatesBean>() {
            @Override
            public void onCompleted() {
                WeiboDialogUtils.closeDialog(activity.mWeiboDialog);
            }

            @Override
            public void onError(Throwable e) {
                WeiboDialogUtils.closeDialog(activity.mWeiboDialog);
            }

            @Override
            public void onNext(CatesBean bean) {
                WeiboDialogUtils.closeDialog(activity.mWeiboDialog);
                if (bean.isSuccess()) {
                    if (null == bean.getData()) {
                        tvLoadPrompt.setText("无更多数据");
                        return;
                    }
                    if (page == 1) {
                        list.clear();
                    }
                    list.addAll(bean.getData().getData());
                    if (bean.getData().getData().size() < 100 && bean.getData().getData().size() > 0) {
                    } else if (bean.getData().getData().size() >= 100) {
                        tvLoadPrompt.setText("正在加载");
                    } else {
                        tvLoadPrompt.setText("无更多数据");
                    }
                    adapter.setDataList(list);
                    adapter2.setDataList(list);
                }
            }
        });
    }
    @Override
    public void initData() {
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                activity.finish();
            }
            break;

            case R.id.nonetwork: {
            }
            break;
            case R.id.resultclick: {
            }
            break;
            case R.id.arror_top: {
                recyclerView.smoothScrollToPosition(0);
                arrorTop.setVisibility(View.GONE);
            }
            break;
            default:
                break;
        }
    }

    public void toDetail(){
        Bundle b = new Bundle();
        b.putSerializable("itemId", ItemId);
        startActivity(TbProductDetailActivity.class, b);
    }

    public void toset(String message) {
        new CommonDialog.Builder(activity)
                .setTitle("提示")
                .setMessage(message)
                .setdialogPostive("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                }).show();
    }

    public void setRecycleType1() {
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, LinearLayoutManager.VERTICAL));
        recyclerView.setAdapter(adapter2);
    }

    public void setRecycleType2() {
        setRcycleview(recyclerView, adapter);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getRecycleType(String  s) {
        activity.recycleType=s;
        if(s.equals("2")){
            setRecycleType2();
        }else{
            setRecycleType1();
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        Siteid = activity.sp.getString("Siteid", "");
        Adzoneid = activity.sp.getString("Adzoneid", "");
    }
}
